<?php
declare(strict_types=1);
namespace App\Services;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Response;

/**
 * csv导出
 * Class CSV
 * @package App\Service
 */
class CsvService
{
    public static function export(array $head,array $body,string $file_name)
    {
        $head_keys = array_keys($head);
        $head_values = array_values($head);
        $fileData = self::utfToGbk(implode(',',$head_values)) . "\n";

        if(strpos($file_name,'.') === false){
            $file_name .= '.csv';
        }

        foreach ($body as $value) {
            $temp_arr = [];
            foreach($head_keys as $key){
                $temp_arr[] = $value[$key] ?? '';
            }
            $fileData .= self::utfToGbk(implode(',',$temp_arr)) . "\n";
        }

        $response = new Response();
        $content_type = 'text/csv';
        return $response->withHeader('content-description', 'File Transfer')
            ->withHeader('content-type', $content_type)
            ->withHeader('content-disposition', "attachment; filename={$file_name}")
            ->withHeader('content-transfer-encoding', 'binary')
            ->withHeader('pragma', 'public')
            ->withBody(new SwooleStream($fileData));
    }

    /**
     * 字符转换（utf-8 => GBK）
     * @param $data
     * @return false|string
     */
    static function utfToGbk($data)
    {
        return iconv('utf-8', 'GBK', $data);
    }

}